// pages/biz/killHome/killHome.js
import Serv from './killHomeServ';
var regeneratorRuntime = require("../../../../lib/js/runtime-module.js")
import util from '../../../../utils/util2'
const app = getApp()
const setScrollHeight = app.setScrollHeight
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{
        name: "正在秒杀"
      },
      {
        name: "准备秒杀"
      }, 
      {
        name: "秒杀结束"
      }
    ], //展示的数据
    regionValue:[],
    tabIdx: 0,
    isShow: false,
    modalTime: ' ',
    currentTime: 21,
    tabBar: {
      home: '../../kill/killHome/killHome',
      mine: '../orderList/orderList'
    },
    killHome: {},
    showImgUrl: [
      'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/mideadc-miniprogram/images/killhome/1.png',
      'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/mideadc-miniprogram/images/killhome/2.png',
      'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/mideadc-miniprogram/images/killhome/3.png',
      'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/mideadc-miniprogram/images/killhome/4.png',
      'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/mideadc-miniprogram/images/killhome/5.png',
      'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/mideadc-miniprogram/images/killhome/6.png',
    ],
    showImgIndex: 1000,
    
    tabIndex: null,
    index: 0,
    isShowMark: false,
    price: {
      bottomValue: null,
      topValue: null,
      isshow: false,
      isflag: false,
      priceIndex: 0,
      priceIndex_sub: 0,
      value: '',
      options: {
        0: [{
            id: 0,
            value: '不限',
          },
          {
            id: 0,
            value: '40万以下',
            max: 400000,
            min: 0
          },
          {
            id: 0,
            value: '40-60万',
            max: 600000,
            min: 400000
          },
          {
            id: 0,
            value: '60-80万',
            max: 800000,
            min: 600000
          },
          {
            id: 0,
            value: '80-100万',
            max: 1000000,
            min: 800000
          },
          {
            id: 0,
            value: '100-150万',
            max: 1500000,
            min: 1000000
          },
          {
            id: 0,
            value: '150-200万',
            max: 2000000,
            min: 1500000
          },
          {
            id: 0,
            value: '200万以上',
            min: 2000000
          },
        ],
        1: [{
            id: 0,
            value: '6000元/㎡以下',
            max: 6000,
            min: 0
          },
          {
            id: 0,
            value: '6000-8000元/㎡',
            max: 8000,
            min: 6000
          },
          {
            id: 0,
            value: '8000-10000元/㎡',
            max: 10000,
            min: 8000
          },
          {
            id: 0,
            value: '10000-12000元/㎡',
            max: 12000,
            min: 10000
          },
          {
            id: 0,
            value: '12000-14000元/㎡',
            max: 14000,
            min: 12000
          },
          {
            id: 0,
            value: '14000-20000元/㎡',
            max: 20000,
            min: 14000
          },
          {
            id: 0,
            value: '20000元以上',
            min: 20000
          },
        ]
      }
    },
    sort: {
      isshow: false,
      isflag: false,
      sortIndex: 0,
      options: [{
          id: '0',
          value: '全部',
        }, {
          id: '1',
          value: '房源',
        },
        {
          id: '2',
          value: '停车位',
        },
        {
          id: '3',
          value: '商铺',
        },{
          id: '4',
          value: '日常快消',
        },
        {
          id: '5',
          value: '家电数码',
        },
        {
          id: '6',
          value: '服饰箱包',
        },
        {
          id: '7',
          value: '其他类型',
        }
      ]
    },
    firstStatus: 0,
    pageSize: 10,
    hidden: true,
    seckillActivity: [],
    seckillTimeIntervalId: null,
    customItem: '全部',
    disabled: false,
    productDeType: [4, 5, 6, 7],
    productHouseType: [1, 2, 3],
    current: 0,
  },
  //模拟秒杀点击下一页
  next: function(e) {
    let {
      showImgIndex,
      showImgUrl
    } = this.data
    showImgIndex += 1
    this.setData({
      showImgIndex
    })
    if (showImgIndex == showImgUrl.length) {
      this.setData({
        firstStatus: 0
      })
    }
  },
  // 请求正在秒杀
  async getBeginList(parmas) {
    let {
      beginList
    } = this.data
    let beginData = await Serv.getBeginList(parmas)
    let {
      rows,
      success
    } = beginData
    //如果pageNo大于2说明是分页
    //todo要执行倒计时放入列表
    //console.log(rows, "rows___")
    if (success) {
      rows && rows.map((item, idx) => {
        //console.log(rows[idx])
        rows[idx].dayObj = util.dayTo(item.endTime)
        rows[idx].endTime = util.formatDate(item.endTime, 2)
      })
      if (parmas.pageNo > 1) {
        let start = beginList && beginData.pageNo > 1 ? beginList.length : 0
        const updateItems = rows.reduce((updateItems, item, index) => {
          const key = `beginList[${start + index}]`;
          updateItems[key] = item;
          return updateItems;
        }, {})
        this.setData(updateItems)
      } else {
        this.setData({
          beginList: rows,
        })
      }
    } else {
      this.setData({
        beginList: [],
        //tabIdx:1
      })
    }
  },
  //请求准备秒杀
  async getNotBeginList(parmas) {
    let {
      notBeginList
    } = this.data
    let notBeginData = await Serv.getNotBeginList(parmas)
    let {
      rows,
      success
    } = notBeginData
    //console.log(rows, 'rows---')
    if (success) {
      rows && rows.map((item, idx) => {
        //console.log(rows[idx])
        rows[idx].dayObj = util.dayTo(item.startTime)
        rows[idx].startTime = util.formatDate(item.startTime, 2)
      })
      if (parmas.pageNo > 1) {
        let start = notBeginList ? notBeginList.length : 0
        const updateItems = rows.reduce((updateItems, item, index) => {
          const key = `notBeginList[${start + index}]`;
          updateItems[key] = item;
          return updateItems;
        }, {})
        this.setData(updateItems)
      } else {
        this.setData({
          notBeginList: rows,
        })
      }
      this.setData({
        notBeginData: {
          total: notBeginData.total,
          pageNo: notBeginData.pageNo
        },
      })
    } else {
      this.setData({
        notBeginList: []
      })
    }
  },
  //请求结束秒杀
  async getEndBeginList(parmas) {
    let {
      endBeginList
    } = this.data
    let endBeginData = await Serv.getEndBeginList(parmas)
    let {
      rows,
      success
    } = endBeginData
    if (success) {
      rows && rows.map((item, idx) => {
        //console.log(rows[idx])
        rows[idx].startTime = util.formatDate(item.startTime, 2)
        rows[idx].endTime = util.formatDate(item.endTime, 2)
      })
      if (parmas.pageNo > 1) {
        let start = endBeginList && endBeginData.pageNo > 1 ? endBeginList.length : 0
        const updateItems = rows.reduce((updateItems, item, index) => {
          const key = `endBeginList[${start + index}]`;
          updateItems[key] = item;
          return updateItems;
        }, {})
        this.setData(updateItems)
      } else {
        this.setData({
          endBeginList: rows,
        })
      }
      this.setData({
        endBeginData: {
          total: endBeginData.total,
          pageNo: endBeginData.pageNo,
        }
      })
    } else {
      this.setData({
        endBeginList: []
      })
    }
  },
  //活动详情 
  async getseckillDetail(parmas) {
    //发起请求
    let {
      data,
      success
    } = await Serv.getseckillDetail(parmas)
    //如果后端返回不为null
    if (success) {
      if (data) {
        let {
          firstInto,
          seckillActivity,
        } = data
        //第一次进入页面
        if (firstInto == 1) {
          this.showMomi()
          //this.getVerificationCode()
        }
        this.setData({
          seckillActivity,
        })
      } 
    } else {
      this.setData({
        seckillActivity: []
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onLoad(option) {
    let that = this
    //option.productId 为扫码跳转时获取productId
    setScrollHeight('#navbar').then(res=>{
      that.setData({
        scrollHeight:res
      })
    })
    this.setData({
      seckillActivityId: option.seckillActivityId || option.productId
    })
    if(option.seckillActivityId || option.productId){
      wx.setStorageSync('seckillActivityId', option.seckillActivityId || option.productId)
    }
    if (!wx.getStorageSync('authName')) {
      console.log(222)
      wx.navigateTo({
        url: '/pages/biz/login/login',
      })
    }
    //是否模拟秒杀
    if (option && option.firstStatus) {
      this.showMomi()
    }
    let parmas = {
      seckillActivityId: option.seckillActivityId || option.productId || wx.getStorageSync('seckillActivityId')
    }
    //活动详情请求
    this.getseckillDetail(parmas)
    this.queryList()
  },
  //打开模拟秒杀
  showMomi() {
    console.log('adsfadfdsafs')
    this.setData({
      showImgIndex: 1000,
      firstStatus: 1
    }, () => {
      //关闭活动弹出框
      this.hideDialog()
    })
  },

  // 筛选下拉
  _toggleTab: function(e) {
    console.log(e)
    let data = this.data || {}
    let tabindex = e.currentTarget.dataset.tabindex
    console.log(e.currentTarget)
    let arr = ['area','price','sort']
    if (this.data.tabIndex === tabindex) {
      // return false;
      console.log('????????????????',arr[tabindex])
      data[arr[tabindex]].isShow = false
    } else {
      // 其他tab的下拉项隐藏
      data.price.isshow = false
      data.sort.isshow = false
    }
    // 当前点击下拉项显示
    data[{
      0: 'area',
      1: 'price',
      2: 'sort'
    }[tabindex]]['isshow'] = !data[{
      0: 'area',
      1: 'price',
      2: 'sort'
    }[tabindex]]['isshow']
    this.setData({ ...data,
      tabIndex: tabindex,
      isShowMark: true
    })
    //this.triggerEvent('changeTab', { tabIndex: this.data.tabIndex })
  },

  _hide: function() {
    let data = this.data || {}
    // 其他tab的下拉项隐藏
    data.price.isshow = false
    data.sort.isshow = false
    this.setData({ ...data,
      isShowMark: false,
      tabIndex: null
    })
  },
  /*查询条件*/
  cahngeInput: function(e) {
    let changeType = e.currentTarget.dataset.changetype.split('_')
    let [name = '', value = ''] = changeType
    let isShowMark = this.data.isShowMark
    console.log('cahngeInput...', e)
    if (name == 'priceType') {
      let price = this.data.price
      price.priceIndex = value
      // price.isshow=false
      this.setData({
        price
      })
      console.log(price, "price1---------")
    } else if (name == 'priceRangeItem') {
      let price = this.data.price
      price.priceIndex_sub = value
      price.isshow = false
      price.isflag = true
      price.topValue = null
      price.bottomValue = null
      isShowMark = false
      this.setData({
        price,
        isShowMark,
        tabIndex: null
      })
    }
    /*商品类型*/
    else if (name == 'sort') {
      let sort = this.data.sort
      sort.sortIndex = value
      sort.isshow = false
      sort.isflag = true
      isShowMark = false
      this.setData({
        sort,
        isShowMark,
        tabIndex: null
      })
      console.log(this.data.sortIndex)
    }
    /*--------根据筛选发起请求-------------*/
    this.queryList()
  },
  formSubmit: function(e) {
    let {
      price,
      isShowMark
    } = this.data;
    console.log('form发生了submit事件，携带数据为：', e.detail.value, e)
    price.bottomValue = e.detail.value.bottom
    price.topValue = e.detail.value.top
    isShowMark = false
    price.isshow = false
    price.isflag = false
    this.setData({
      price,
      isShowMark
    })
    this.cahngeInput(e)
  },
  //关注收藏
  async favoriteCreate(parmas) {
    let result = await Serv.favoriteCreate(parmas)
    if (result.success) { // 接口请求成功
      return true
    } else { // 接口请求失败
      wx.showToast({
        title: result.msg,
        icon: 'none'
      })
      return false
    }
  },
  like: function(e) {
    let {
      id,
      follow,
      idx,
      type
    } = e.currentTarget.dataset
    let followCopy = follow == 0 ? 1 : 0
    this.favoriteCreate({
      seckillProductId: id,
      type: 3,
      follow: followCopy
    }).then((result) => {
      // console.log(result)
      //todo 收藏逻辑
      if (result) { // 收藏或者取消收藏成功
        // let {
        //   beginList,
        //   notBeginList
        // } = this.data
        // console.log(idx)
        let str
        if (type == 1) { //正在秒杀
          str = `beginList[${idx}].follow`
        }
        if (type == 0) { //准备秒杀
          str = `notBeginList[${idx}].follow`
        }
        if (type == 2) { //结束秒杀
          str = `endBeginList[${idx}].follow`
        }
        this.setData({
          [str]: followCopy
        })
      }
    })
  },
  router: function(e) {
    let router = e.currentTarget.dataset.router
    wx.navigateTo({
      url: router
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.queryList()
    //新增需求正在没有数据跳准备
    setTimeout(() => {
      let { beginList } = this.data
      if (beginList.length == 0) {
        this.setData({
          tabIdx: 1
        },()=>{
          this.queryList()
        })
      }
    }, 500)

  },
  bindRegionChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail)
    /*--------根据筛选发起请求-------------*/
    let {
      price,
      area,
      sort,
      seckillTimeIntervalId,
      pageSize
    } = this.data
    this.setData({
      region: e.detail.value,
      code: e.detail.code
    })
    //todo 更改数据源
    let code = e.detail.code
    let province
    if (code[0] == '110000') {
      province = '110100'
    } else {
      province = code[0] ? code[0] : ''
    }
    let city = code[1] ? code[1] : ''
    let county = code[2] ? code[2] : ''
    e.detail.code = [province, city, county]
    this.setData({
      province,
      city,
      county,
    })
    wx.setStorageSync("code", e.detail)
    this.queryList()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearTimeout(this.data.Timer)
  },
  getCode: function(options) {
    var that = this;
    var currentTime = that.data.currentTime
    console.log()
    var interval = setInterval(function() {
      currentTime--;
      that.setData({
        modalTime: currentTime + '秒'
      })
      if (currentTime <= 0) {
        for (var i = 0; i <= interval; i++) {
          clearInterval(interval)
        }
        that.setData({
          modalTime: '我已阅读',
          currentTime: 21,
          disabled: false
        })
      }
    }, 1000)
  },
  getVerificationCode() {
    this.getCode();
    var that = this
    that.setData({
      disabled: true
    })
  },
  //隐藏弹框
  hideDialog() {
    this.setData({
      isShow: false
    })
  },
  //展示弹框
  showDialog() {
    this.setData({
      isShow: true
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let {
      notBeginData,
      notBeginList,
      endBeginData,
      endBeginList,
      beginData,
      beginList,
      tabIdx,
    } = this.data;
    if (tabIdx == 0) {
      //秒杀分页
      this.pagination(beginData, beginList)
    } else if (tabIdx == 1) {
      //准备秒杀分页
      this.pagination(notBeginData, notBeginList)
    } else if (tabIdx == 2) {
      //结束秒杀分页
      this.pagination(endBeginData, endBeginList)
    }
  },
  // 改变tab栏的时候
  changeTab(e) {
    console.log(e.currentTarget.dataset)
    let {
      tabindex
    } = e.currentTarget.dataset
    this.setData({
      tabIdx: tabindex
    })
    this.queryList()
  },
  queryList(pageNo = 1) {
    let {
      tabIdx,
      price,
      area,
      sort,
      province,
      city,
      county,
      pageSize,
      seckillActivityId
    } = this.data
    let params = {
      province,
      city,
      county,
      maxPrice: price.topValue ? price.topValue : price.options[price.priceIndex][price.priceIndex_sub].max,
      minPrice: price.bottomValue ? price.bottomValue : price.options[price.priceIndex][price.priceIndex_sub].min,
      productType: sort.sortIndex,
      priceIndex: price.priceIndex,
      pageNo,
      seckillActivityId,
      pageSize
    }
    if (tabIdx == 0) {
      //秒杀发起请求
      this.getBeginList(params)
    } else if (tabIdx == 1) {
      //准备秒杀发起请求
      this.getNotBeginList(params)
    } else if (tabIdx == 2) {
      //结束秒杀发起请求
      this.getEndBeginList(params)
    }
  },
  pagination(data = {}, list) {
    
    let { pageNo = 0, total=0 }  = data
    if (list&&list.length < data.total) {
      this.setData({
        loading: true
      })
      pageNo += 1
      /*--------根据筛选发起请求-------------*/
      setTimeout(() => {
        this.queryList(pageNo)
        this.setData({
          loading: false
        })
      })
    }else{
      return false
    }
  },
  toggle: function () {
    let { current, showImgUrl, showImgIndex } = this.data
    this.setData({
      current: current >= showImgUrl.length - 1 ? 0 : current + 1,
      showImgIndex: showImgIndex + current
    })
    console.log(current)
    if (current + 1 == showImgUrl.length) {
      console.log(current, showImgUrl.length)
      this.setData({
        firstStatus: 0
      })
    }
  },
  onImageLoaded() {
    let { showImgUrl } = this.data
    this._imageLoadedCount = this._imageLoadedCount ? this._imageLoadedCount + 1 : 1
    console.log(this._imageLoadedCount)
    if (this._imageLoadedCount === showImgUrl.length) {
      console.log('所有图片加载完成')
    }
  },
  onUnload: function () {
    for (var i = 0; i <= 1000; i++) {
      clearInterval(i);
    }
  },
})